#pragma once
#include <chrono>
#include <boost/filesystem.hpp>
#include "nlohmann/json.hpp"
#include "server/config/config.h"
#include "state_machin_define.h"

namespace ArrowWebCodeView
{
namespace SessionMachine
{

class StateSendPathList : public StateBase
{

private:
    using Data = StateBase::Data;
    using StateEnum = StateBase::StateEnum;
    using Msg = StateBase::Msg;

public:
    StateSendPathList() {}

public:
    virtual ~StateSendPathList() {}

    /**
     * @description: 初始化 创建状态的时候调用一次
     * @param {AreaMachineData&} data
     * @return {*}
     */
    virtual void Init(const Data& data)
    {
    }

    /**
     * @description: 当从其他状态迁移到当前状态调用
     * @param {AreaMachineData*} pData
     * @return {*}
     */
    virtual void Start(Data* pData)
    {
    }

    /**
     * @description: 处理消息
     * @param {Data*} pData
     * @param {Msg} msg
     * @return {*}
     */
    virtual StateEnum HandleMsg(Data* pData, Msg msg, const std::string& strMsg, std::string& strResult)
    {
        if(msg != Msg::Folder)
        {
            return StateEnum::SendPathList;
        }
        nlohmann::ordered_json jPathList;
        boost::filesystem::path path(strMsg);
        if (strMsg == AppConfig::Instance()->DefalutFolder())
        {
            jPathList["parent"] = strMsg;
            jPathList["main"] = strMsg;
        }
        else
        {
            jPathList["parent"] = path.parent_path().string();
            jPathList["main"] = strMsg;
        }
        for (auto& p : boost::filesystem::directory_iterator(path))
        {
            if (boost::filesystem::is_directory(p))
            {
                jPathList["folder"].push_back(p.path().filename().string());
                continue;
            }

            if (boost::filesystem::is_regular_file(p))
            {
                jPathList["file"].push_back(p.path().filename().string());
                continue;
            }
        }

        nlohmann::ordered_json jReslut;
        jReslut["cmd"] = MsgEnumStr::ItemStr(msg);
        jReslut["result"] = jPathList;
        strResult = jReslut.dump();
        m_pContext->ChangeState(StateEnum::RecvPath);
        ARROW_LOG_INFO_FMT("getf file path %s success result %s", strMsg.c_str(), strResult.c_str());

        return StateEnum::RecvPath;
    }

    /**
     * @description: 处理定时消息
     * @param {AreaMachineData*} pData
     * @return {*}
     */    
    virtual StateEnum Timer(Data* pData)
    {
        return State();
    }

    /**
     * @description: 当前状态
     * @return {*}
     */
    virtual StateEnum State()
    {
        return StateEnum::SendPathList;
    }

    virtual void Context(ContextType* pContext)
    {
        m_pContext = pContext;
    }

private:
    ContextType* m_pContext = nullptr;

};
}
}